import requests

class httpClient:
    def __init__(self, base_url: str):
        self.base_url = base_url
        self.headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
        }
        self.get_token('admin', 'admin123F')
    def get_token(self, account: str, password: str):
        url = f'{self.base_url}/api.php/v1/tokens'
        data = {
            'account': account,
            'password': password,
        }
        
        try:
            response = requests.post(url, json=data, headers=self.headers)
            response.raise_for_status()
            
            result = response.json()
            token = result.get('token')
            print(token)
            if token:
                self.headers['Token'] = token
                print(self.headers)
                return token
            else:
                raise Exception("无法获取Token，响应中缺少token字段")
        except requests.exceptions.RequestException as e:
            raise Exception(f"获取Token失败: {str(e)}")
   
    def get(self, path: str, params=None):
        """发送GET请求"""
        url = f'{self.base_url}{path}'
        try:
            response = requests.get(url, params=params, headers=self.headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"GET请求失败: {str(e)}")
    
    def post(self, path: str, json=None):
        """发送POST请求"""
        url = f'{self.base_url}{path}'
        try:
            response = requests.post(url, json=json, headers=self.headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"POST请求失败: {str(e)}")
    
    def put(self, path: str, json=None):
        """发送PUT请求"""
        url = f'{self.base_url}{path}'
        try:
            response = requests.put(url, json=json, headers=self.headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"PUT请求失败: {str(e)}")
    
    def delete(self, path: str, params=None):
        """发送DELETE请求"""
        url = f'{self.base_url}{path}'
        try:
            response = requests.delete(url, params=params, headers=self.headers)
            response.raise_for_status()
            return response.json()
        except requests.exceptions.RequestException as e:
            raise Exception(f"DELETE请求失败: {str(e)}")
   